﻿<template>
  <div class="app-container">
    <div class="filter-title">
      <el-form label-position="right"
               label-width="90px">
        <el-form-item :label="$t('video.name')+' :'">
          <el-input v-model="listQuery.name"
                    style="width: 150px"
                    class="filter-item"
                    :placeholder="$t('video.name')"
                    @keyup.enter.native="handleFilter"></el-input>
        </el-form-item>
        <el-form-item :label="$t('video.adName')+' :'">
          <el-input v-model="listQuery.ad_name"
                    style="width: 150px"
                    class="filter-item"
                    :placeholder="$t('video.adName')"
                    @keyup.enter.native="handleFilter"></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.trade')+' :'">
          <el-input v-model="listQuery.trade_name"
                    style="width: 150px"
                    class="filter-item"
                    :placeholder="$t('public.trade')"
                    @keyup.enter.native="handleFilter"></el-input>
        </el-form-item>
        <el-button style="margin-left:20px"
                   class="filter-item"
                   type="primary"
                   icon="el-icon-search"
                   @click="handleFilter">{{ $t('table.search') }}</el-button>
        <el-button v-if="permission.add"
                   style="margin-left: 10px;float:right"
                   class="filter-item"
                   type="primary"
                   icon="el-icon-edit"
                   @click="handleCreate">{{ $t('table.add') }}</el-button>
        <el-button style="margin-left: 10px"
                   class="filter-item"
                   type="primary"
                   @click="handleRefresh">{{ $t('table.refresh') }}</el-button>
        <div v-show="!showSearchItem"
             class="showDown"
             @click.prevent="showSearchItem = true">
          <i class="el-icon-d-arrow-right"></i>
        </div>
        <div v-show="showSearchItem"
             class="showUp"
             @click.prevent="showSearchItem = false">
          <i class="el-icon-d-arrow-left"></i>
        </div>
      </el-form>
    </div>
    <div v-show="showSearchItem"
         class="filter-container">
      <el-form label-position="right"
               label-width="90px">
        <el-form-item :label="$t('public.linkman')+' :'">
          <el-input v-model="listQuery.region_name"
                    style="width: 150px"
                    class="filter-item"
                    :placeholder="$t('public.linkman')"
                    @keyup.enter.native="handleFilter"></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.checkStatus')+' :'">
          <el-select v-model="listQuery.check_status"
                     clearable
                     style="width: 150px"
                     class="filter-item"
                     :placeholder="$t('public.checkStatus')">
            <el-option v-for="item in statusOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('video.uploadTime')+' :'">
          <div class="filter-item">
            <el-date-picker v-model="listQuery.startUploadTime"
                            :picker-options="pickerOptionsB"
                            type="date"
                            :placeholder="$t('video.startUploadTime')"
                            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </div>
          <div class="filter-item">
            <el-date-picker v-model="listQuery.endUploadTime"
                            :picker-options="pickerOptionsE"
                            type="date"
                            :placeholder="$t('video.endUploadTime')"
                            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <el-table :key="tableKey"
              v-loading="listLoading"
              :data="list"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255,255,255,0.2)"
              border
              fit
              highlight-current-row
              style="width: 100%min-height:1000px">
      <el-table-column fixed="left"
                       align="center"
                       :label="$t('table.id')"
                       width="65">
        <template slot-scope="scope">
          <span>{{ (listQuery.page-1)*listQuery.limit+scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       :label="$t('video.name')">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       :label="$t('video.adName')">
        <template slot-scope="scope">
          <span>{{ scope.row.ad_name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       :label="$t('public.trade')">
        <template slot-scope="scope">
          <span>{{ scope.row.trade_name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       :label="$t('public.region')">
        <template slot-scope="scope">
          <span>{{ scope.row.region_name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       :label="$t('public.checkStatus')">
        <template slot-scope="scope">
          <span :class="statusColor(scope.row.check_status)">{{ statusEsSecond(scope.row.check_status) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       show-overflow-tooltip
                       :label="$t('video.uploadTime')">
        <template slot-scope="scope">
          <span>{{ scope.row.upload_time }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right"
                       align="center"
                       :label="$t('table.actions')"
                       :width="operWidth"
                       class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary"
                     size="mini"
                     @click="handleRead(scope.row)">{{ $t('table.read') }}</el-button>
          <el-button v-if="permission.update"
                     type="primary"
                     size="mini"
                     @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="permission.review"
                     type="primary"
                     size="mini"
                     @click="handleReview(scope.row)">{{ $t('table.review') }}</el-button>
          <el-button v-if="permission.del"
                     size="mini"
                     type="danger"
                     @click="handleModifyStatus(scope.row,'deleted')">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background
                     :current-page="listQuery.page"
                     :page-sizes="[10,20,30,50]"
                     :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 编辑 -->
    <el-dialog v-loading="updateLoading"
               :title="textMap[dialogStatus]"
               :visible.sync="dialogFormVisible"
               :before-close="handleClose"
               element-loading-text="正在上传视频请耐心等待"
               element-loading-spinner="el-icon-loading"
               element-loading-background="rgba(0, 0, 0, 0.5)">
      <el-form ref="dataForm"
               :rules="rules"
               :model="temp"
               label-position="right"
               label-width="35%"
               style="width: 400px margin-left:120px"
               size="small">
        <el-form-item v-if="dialogStatus==='review'"
                      :label="$t('video.code')+' :'">
          <span>{{ temp.code }}</span>
        </el-form-item>
        <el-form-item :label="$t('video.type')+' :'"
                      prop="video_type">
          <el-radio-group v-if="dialogStatus!=='review'"
                          v-model="video_type"
                          @change="changCode('url')">
            <el-radio label="1">视频</el-radio>
            <el-radio label="2">图片</el-radio>
          </el-radio-group>
          <span v-else>{{ videoType(video_type) }}</span>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='review'"
                      :label="$t('video.video')+' :'">
          <div>
            <li v-if="temp.url"
                class="videoCode">
              <el-button type="primary"
                         size="mini"
                         @click="visibleVideo = true">预览</el-button>
            </li>
          </div>
        </el-form-item>
        <el-form-item v-else
                      :label="$t('video.video')+' :'"
                      prop="url">
          <div>
            <li v-show="temp.url"
                class="videoCode">
              <el-button type="primary"
                         size="mini"
                         @click="visibleVideo = true">预览</el-button>
              <el-button type="danger"
                         size="mini"
                         @click="changCode('url')">删除</el-button>
            </li>
            <div v-show="!temp.url"
                 class="videoLoading"
                 tabindex="0">
              <i class="el-icon-plus"></i>
              <input id="my-video"
                     ref="file"
                     type="file"
                     class="uploadVideoInput"
                     @change="(e)=>{return submitUpload(e,'url')}" />
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='review'"
                      :label="$t('video.name')+' :'">
          <span>{{ temp.name }}</span>
        </el-form-item>
        <el-form-item v-else
                      :label="$t('video.name')+' :'"
                      prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='review'"
                      :label="$t('video.adName')+' :'">
          <span>{{ temp.ad_name }}</span>
        </el-form-item>
        <el-form-item v-else-if="type === 1"
                      :label="$t('video.adName')+' :'"
                      prop="ad_id">
          <select-page :id="temp.ad_id"
                       :name="temp.ad_name"
                       style="width:200px"
                       key-field="id"
                       show-field="name"
                       :data="adOptions"
                       placeholder="请选择广告主"
                       :count="adNameCount"
                       :page-size="pageSize"
                       @getList="getAdNameList"
                       @values="getAdNameid"></select-page>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='review'"
                      :label="$t('public.trade')+' :'">
          <span>{{ temp.trade_name }}</span>
        </el-form-item>
        <el-form-item v-else
                      :label="$t('public.trade')+' :'"
                      prop="trade_id">
          <select-page :id="temp.trade_id"
                       :name="temp.trade_name"
                       placeholder="请选择行业"
                       key-field="id"
                       show-field="name"
                       :data="industryOptions"
                       :count="industryCount"
                       :page-size="pageSize"
                       style="width:200px"
                       @getList="getIndustryList"
                       @values="getIndustryid"></select-page>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='review'"
                      :label="$t('video.timeLength')+' :'">
          <span>{{ temp.time_length }}&nbsp;秒</span>
        </el-form-item>
        <el-form-item v-else
                      :label="$t('video.timeLength')+' :'"
                      prop="time_length">
          <el-input-number v-model="temp.time_length"
                           controls-position="right"
                           :min="1"
                           :disabled="video_type==='1'?'disabled':false"></el-input-number>&nbsp;秒
        </el-form-item>
        <el-form-item v-if="dialogStatus==='review' && temp.video_ratio"
                      :label="$t('video.videoRatio')+' :'">
          <span>{{ temp.video_ratio }}</span>
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='review'"
                      :label="$t('video.videoRatio')+' :'"
                      prop="video_ratio">
          <el-input v-model="temp.video_ratio"
                    disabled></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus==='review' && temp.video_px"
                      :label="$t('video.videoPx')+' :'">
          <span>{{ temp.video_px }}</span>
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='review'"
                      :label="$t('video.videoPx')+' :'"
                      prop="video_px">
          <el-input v-model="temp.video_px"
                    disabled></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='review'"
                      :label="$t('video.producer')+' :'">
          <span>{{ temp.producer }}</span>
        </el-form-item>
        <el-form-item v-else
                      :label="$t('video.producer')+' :'"
                      prop="producer">
          <el-input v-model="temp.producer"></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='review' && temp.describe"
                      :label="$t('video.describe')+' :'">
          <span>{{ temp.describe }}</span>
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='review'"
                      :label="$t('video.describe')+' :'"
                      prop="describe">
          <el-input v-model="temp.describe"
                    type="textarea"></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='review'"
                      :label="$t('public.checkStatus')+' :'"
                      prop="check_status">
          <el-radio-group v-model="temp.check_status">
            <el-radio :label="0">审核中</el-radio>
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="2">未通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='review' && temp.check_status === 2"
                      :label="$t('public.auditOpinion')+' :'"
                      prop="check_remark">
          <el-input v-model="temp.check_remark"
                    type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button v-if="dialogStatus=='create'"
                   type="primary"
                   :disabled="!createDisabled"
                   @click="createData">{{ $t('table.confirm') }}</el-button>
        <el-button v-else-if="dialogStatus=='review'"
                   type="primary"
                   :disabled="!updateDisabled"
                   @click="reviewData">{{ $t('table.confirm') }}</el-button>
        <el-button v-else
                   type="primary"
                   :disabled="!updateDisabled"
                   @click="updateData">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog :title="textMap[dialogStatus]"
               :visible.sync="dialogFormRead">
      <el-form :model="temp"
               label-position="right"
               label-width="40%"
               style="width: 400px margin-left:120px">
        <el-form-item :label="$t('video.code')+' :'">
          <span>{{ temp.code }}</span>
        </el-form-item>
        <el-form-item :label="$t('video.video')+' :'"
                      prop="url">
          <div>
            <li v-if="temp.url"
                class="videoCode">
              <!-- <span>{{  temp.url  }}</span> -->
              <el-button type="primary"
                         size="mini"
                         @click="visibleVideo = true">预览</el-button>
            </li>
          </div>
        </el-form-item>
        <el-form-item :label="$t('video.name')+' :'">
          <span>{{ temp.name }}</span>
        </el-form-item>
        <el-form-item v-if="type === 1"
                      :label="$t('video.adName')+' :'">
          <span>{{ temp.ad_name }}</span>
        </el-form-item>
        <el-form-item :label="$t('public.linkman')+' :'">
          <span>{{ temp.region_name }}</span>
        </el-form-item>
        <el-form-item :label="$t('public.trade')+' :'">
          <span>{{ temp.trade_name }}</span>
        </el-form-item>
        <el-form-item :label="$t('video.timeLength')+' :'">
          <span>{{ temp.time_length }}&nbsp;秒</span>
        </el-form-item>
        <el-form-item v-if="temp.video_ratio"
                      :label="$t('video.videoRatio')+' :'">
          <span>{{ temp.video_ratio }}</span>
        </el-form-item>
        <el-form-item v-if="temp.video_px"
                      :label="$t('video.videoPx')+' :'">
          <span>{{ temp.video_px }}</span>
        </el-form-item>
        <el-form-item :label="$t('video.producer')+' :'">
          <span>{{ temp.producer }}</span>
        </el-form-item>
        <el-form-item v-if="temp.describe"
                      :label="$t('video.describe')+' :'">
          <span>{{ temp.describe }}</span>
        </el-form-item>
        <el-form-item :label="$t('public.checkStatus')+' :'">
          <span>{{ statusEsSecond(temp.check_status) }}</span>
        </el-form-item>
        <el-form-item v-if="temp.check_status === 2"
                      :label="$t('public.auditOpinion')+' :'">
          <span>{{ temp.check_remark }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 视频预览 -->
    <el-dialog title="视频源"
               :model="temp"
               :visible.sync="visibleVideo"
               width="30%"
               :before-close="beforeVideoClose">
      <video v-if="temp.url !='' && video_type === '1'"
             id="video"
             ref="video"
             :src="temp.url"
             width="100%"
             height="auto"
             controls="controls">您的浏览器不支持视频播放</video>
      <img v-else-if="temp.url !=''"
           :src="temp.url"
           style="width:100%;height:auto" />
    </el-dialog>
    <video id="video_hideen"
           ref="video_hideen"
           :src="temp.url"
           style="display:none">您的浏览器不支持视频播放</video>
  </div>
</template>
<script>
import selectPage from "@/views/select/SelectPage"; // 分页选择控件
import { getToken } from "@/utils/auth"; // get token from cookie

export default {
  name: "VideoApplication",
  components: {
    "select-page": selectPage
  },
  data() {
    const name = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 20) {
          callback(new Error("视频名称长度不能大于20个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)[\u4e00-\u9fff\w]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error(
                "视频名称只能包含汉字、英文、“_”和数字且不为纯数字或纯符号"
              )
            );
          }
        }
      } else {
        callback(new Error("请填写视频名称"));
      }
    };
    const describe = (rule, value, callback) => {
      // return false
      if (value.length > 200) {
        callback(new Error("视频描述不得超过200个字符"));
      } else {
        callback();
      }
    };
    const remark = (rule, value, callback) => {
      if (value) {
        if (value.length <= 0) {
          callback(new Error("请输入审核意见"));
        } else if (value.length > 300) {
          callback(new Error("审核意见不能超过300个字符"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入审核意见"));
      }
    };
    const video_type = (rule, value, callback) => {
      if (!this.video_type) {
        callback(new Error("请选择视频源类型"));
      } else {
        callback();
      }
    };

    const producer = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 32) {
          callback(new Error("制作单位长度不能大于32个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)(?!(\、+)$)[\u4e00-\u9fff\w\、]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error(
                "制作单位只能包含汉字、英文、“_”、“（”、“）”和数字且不为纯数字或纯符号"
              )
            );
          }
        }
      } else {
        callback(new Error("请填写制作单位"));
      }
    };
    return {
      showSearchItem: false,
      abc: [],
      list2: "",
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      updateLoading: false,
      statusOptions: [
        {
          value: 0,
          label: "审核中"
        },
        {
          value: 2,
          label: "未通过"
        }
      ],
      listQuery: {
        page: 1,
        limit: 20,
        name: "",
        ad_name: "",
        trade_name: "",
        region_name: "",
        startUploadTime: "",
        endUploadTime: "",
        check_status: ""
      },
      temp: {
        id: undefined,
        name: "",
        ad_id: "",
        ad_name: "",
        url: "",
        trade_id: "",
        producer: "",
        time_length: undefined,
        describe: "",
        check_remark: "",
        video_ratio: "",
        video_px: "",
        file_md5: ""
      },
      video_type: "1",
      dialogFormVisible: false,
      dialogFormRead: false,
      dialogStatus: "",
      visibleVideo: false,
      textMap: {
        update: "更新",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      rules: {
        video_type: [
          {
            required: true,
            message: "请选择视频源类型",
            trigger: "change",
            validator: video_type
          }
        ],
        name: [{ required: true, trigger: "blur", validator: name }],
        ad_id: [
          { required: true, message: "请填写广告主编号", trigger: "blur" }
        ],
        url: [{ required: true, message: "请上传视频源", trigger: "blur" }],
        trade_id: [{ required: true, message: "请选择行业", trigger: "blur" }],
        time_length: [
          { required: true, message: "请填写视频时长", trigger: "blur" }
        ],
        producer: [{ required: true, trigger: "blur", validator: producer }],
        describe: [{ trigger: "blur", validator: describe }],
        check_status: [
          { required: true, message: "请审核", trigger: "change" }
        ],
        check_remark: [{ required: true, trigger: "blur", validator: remark }]
      },
      createDisabled: true,
      updateDisabled: true,
      loading: false,
      industryOptions: [],
      adOptions: [],
      type: "",
      ad: {
        id: undefined,
        name: ""
      },
      pageSize: 20,
      adNameCount: undefined,
      areaCount: undefined,
      industryCount: undefined,
      permission: {
        add: false,
        del: false,
        update: false,
        review: false
      },
      pickerOptionsB: {
        // 限制时间
        // selectableRange: ['22:00:00 - 23:59:59','00:00:00 - 02:00:00'],
        // 限制日期
        disabledDate: this.disabledDateB
      },
      pickerOptionsE: {
        disabledDate: this.disabledDateE
      },
      files: ""
    };
  },
  computed: {
    operWidth: function() {
      let itemCount = 1;
      if (this.permission.del) {
        itemCount += 1;
      }
      if (this.permission.update) {
        itemCount += 1;
      }
      if (this.permission.review) {
        itemCount += 1;
      }
      return itemCount * 80 + "px";
    }
  },
  created() {
    if (this.$store.state.permission.jurisdiction === "*") {
      this.permission.add = true;
      this.permission.update = true;
      this.permission.del = true;
      this.permission.review = true;
    } else {
      const jurisdiction = this.$store.state.permission.jurisdiction.split(",");
      jurisdiction.forEach(element => {
        const id = parseInt(element);
        if (id === 157) {
          this.permission.del = true;
        } else if (id === 156) {
          this.permission.update = true;
        } else if (id === 154) {
          this.permission.add = true;
        } else if (id === 155) {
          this.permission.review = true;
        }
      });
    }

    this.type = JSON.parse(getToken()).type;
    if (JSON.parse(getToken()).type !== 1) {
      this.ad.id = JSON.parse(getToken()).id;
      this.ad.name = JSON.parse(getToken()).name;
    }
    this.getList();
  },
  methods: {
    disabledDateB(time) {
      if (this.listQuery.endUploadTime) {
        return (
          time.getTime() >
          new Date(this.listQuery.endUploadTime).getTime() +
          24 * 3600 * 1000 -
          8.64e7
        );
      }
    },
    disabledDateE(time) {
      if (this.listQuery.startUploadTime) {
        return (
          time.getTime() <
          new Date(this.listQuery.startUploadTime).getTime() - 8.64e6
        );
      }
    },
    getAdNameList(pageNumber = 1, search = "") {
      this.getadName(pageNumber, search);
    },
    getAdNameid(data) {
      if (data.length > 0) {
        this.temp.ad_id = data[0].id;
        this.temp.ad_name = data[0].name;
      } else {
        this.temp.ad_id = undefined;
        this.temp.ad_name = "";
      }
    },
    getIndustryList(pageNumber = 1, search = "") {
      this.getIndustry(pageNumber, search);
    },
    getIndustryid(data) {
      if (data.length > 0) {
        this.temp.trade_id = data[0].id;
        this.temp.trade_name = data[0].name;
      } else {
        this.temp.trade_id = undefined;
        this.temp.trade_name = "";
      }
    },
    getList() {
      this.listLoading = true;
      const data = {
        rows: this.listQuery.limit,
        page: this.listQuery.page
      };
      if (this.listQuery.name) {
        data["name"] = this.listQuery.name;
      }
      if (this.listQuery.ad_name) {
        data["ad_name"] = this.listQuery.ad_name;
      }
      if (this.listQuery.trade_name) {
        data["trade_name"] = this.listQuery.trade_name;
      }
      if (this.listQuery.region_name) {
        data["region_name"] = this.listQuery.region_name;
      }
      if (this.listQuery.startUploadTime) {
        data["startUploadTime"] = this.listQuery.startUploadTime;
      }
      if (this.listQuery.endUploadTime) {
        const date = new Date(this.listQuery.endUploadTime);
        data["endUploadTime"] = this.timestampToTime(
          date.getTime() + (60 * 60 * 24 * 1000 - 1)
        );
      }
      if (this.listQuery.check_status || this.listQuery.check_status === 0) {
        data["check_status"] = this.listQuery.check_status;
      }

      const adVideoGetPath = {
        // 获取视频源列表
        company: "STQ",
        api: "pc_AdVideo_getRequestList",
        version: "1.0",
        data: data
      };

      this.socketApi.sendSock(JSON.stringify(adVideoGetPath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleModifyStatus(row) {
      this.$confirm("此操作将永久删除该视频源信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const index = row.url.lastIndexOf("/");
          const str = row.url.substring(index + 1, row.url.length);
          const video_name = { video_id: row.id, video_name: str };

          this.deleteFile(video_name, result => {
            if (result.data.code === 0) {
              this.$message.error(result.data.message);
            } else {
              const deleteVideoPath = {
                company: "STQ",
                api: "pc_AdVideo_deleteVideo",
                version: "1.0",
                data: {
                  id: row.id
                }
              };
              this.socketApi.sendSock(JSON.stringify(deleteVideoPath), res => {
                if (res) {
                  this.socketData(res);
                } else {
                  this.$message.error(" 删除失败 ");
                }
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        ad_id: "",
        url: "",
        trade_id: "",
        producer: "",
        time_length: undefined,
        describe: "",
        check_remark: "",
        video_ratio: "",
        video_px: "",
        file_md5: ""
      };
      this.video_type = "1";
    },
    handleRefresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        name: "",
        ad_name: "",
        trade_name: "",
        region_name: "",
        startUploadTime: "",
        endUploadTime: "",
        check_status: ""
      };
      this.getList();
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      // this.getArea1()
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      // 添加视频
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.createDisabled) {
            this.createDisabled = false;
            this.updateLoading = true;
            const video = new FormData();
            video.append("video", this.files);
            this.updateFile(video, result => {
              if (result.data.code === 0) {
                this.$message.error(result.data.message);
              } else {
                this.temp.file_md5 = result.data.data.file_md5;
                this.temp.url = result.data.data.video_url;
                // 添加视频
                const data = {
                  name: this.temp.name,
                  url: this.temp.url,
                  trade_id: this.temp.trade_id,
                  trade_name: this.temp.trade_name,
                  producer: this.temp.producer,
                  time_length: this.temp.time_length,
                  video_ratio: this.temp.video_ratio,
                  video_px: this.temp.video_px,
                  video_type: this.video_type,
                  file_md5: this.temp.file_md5
                };
                if (this.type !== 1) {
                  data["ad_id"] = this.ad.id;
                  data["ad_name"] = this.ad.name;
                } else {
                  this.adOptions.forEach(item => {
                    if (item.id === this.temp.ad_id) {
                      data["ad_id"] = this.temp.ad_id;
                      data["ad_name"] = this.temp.ad_name;
                    }
                  });
                }

                if (this.temp.describe) {
                  data["describe"] = this.temp.describe;
                }
                const AdVideoPath = {
                  company: "STQ",
                  api: "pc_AdVideo_addVideo",
                  version: "1.0",
                  data: data
                };
                this.socketApi.sendSock(JSON.stringify(AdVideoPath), res => {
                  if (res) {
                    this.socketData(res);
                  } else {
                    this.$message.error(" 添加失败 ");
                  }
                  setTimeout(() => {
                    this.createDisabled = true;
                  }, 1000);
                });
              }
            });
            return false;
          }
        }
      });
    },
    handleReview(row) {
      // 打开审核弹窗
      this.temp = Object.assign({}, row); // copy obj
      this.video_type = this.temp.video_type.toString();
      this.dialogStatus = "review";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate(row) {
      // 打开编辑弹窗
      this.temp = Object.assign({}, row); // copy obj
      this.temp.trade_id = parseInt(this.temp.trade_id);
      this.video_type = this.temp.video_type.toString();
      this.files = "";
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.getIndustry();
      this.getadName();
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleRead(row) {
      // 打开查看弹窗
      this.temp = Object.assign({}, row); // copy obj
      this.video_type = this.temp.video_type.toString();
      this.dialogStatus = "read";
      this.dialogFormRead = true;
    },
    reviewData() {
      // 审核
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.temp.url) {
            if (this.updateDisabled) {
              this.updateDisabled = false;
              const data = {
                id: this.temp.id,
                check_status: this.temp.check_status
              };
              if (this.temp.check_remark) {
                data["check_remark"] = this.temp.check_remark;
              }
              const checkVideoPath = {
                company: "STQ",
                api: "pc_AdVideo_checkVideo",
                version: "1.0",
                data: data
              };
              this.socketApi.sendSock(JSON.stringify(checkVideoPath), res => {
                if (res) {
                  this.socketData(res);
                }
                setTimeout(() => {
                  this.updateDisabled = true;
                }, 1000);
              });
            }
          } else {
            this.$message.error("没有视频源");
          }
        }
      });
    },
    updateData() {
      // 更新视频源信息
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.updateDisabled) {
            this.updateDisabled = false;
            this.updateLoading = true;
            if (this.files) {
              const video = new FormData();
              video.append("video", this.files);
              this.updateFile(video, result => {
                if (result.data.code === 0) {
                  this.$message.error(result.data.message);
                } else {
                  const url = this.temp.url;
                  const index = url.lastIndexOf("/");
                  const video_name = url.substring(index + 1, url.length);
                  this.videoDel(video_name);
                  this.temp.file_md5 = result.data.data.file_md5;
                  this.temp.url = result.data.data.video_url;

                  const data = {
                    id: this.temp.id,
                    name: this.temp.name,
                    ad_id: this.temp.ad_id,
                    url: this.temp.url,
                    trade_id: this.temp.trade_id,
                    trade_name: this.temp.trade_name,
                    producer: this.temp.producer,
                    time_length: this.temp.time_length,
                    describe: this.temp.describe,
                    video_ratio: this.temp.video_ratio,
                    video_px: this.temp.video_px,
                    video_type: this.video_type,
                    file_md5: this.temp.file_md5
                  };
                  if (this.type === 2) {
                    data["ad_name"] = this.temp.ad_name;
                  } else {
                    this.adOptions.forEach(item => {
                      if (item.id === this.temp.ad_id) {
                        data["ad_name"] = item.name;
                      }
                    });
                  }
                  if (this.temp.check_status) {
                    data["check_status"] = this.temp.check_status;
                  }
                  if (this.temp.check_remark) {
                    data["check_remark"] = this.temp.check_remark;
                  }
                  const editVideoPath = {
                    company: "STQ",
                    api: "pc_AdVideo_editVideo",
                    version: "1.0",
                    data: data
                  };
                  this.socketApi.sendSock(
                    JSON.stringify(editVideoPath),
                    res => {
                      if (res) {
                        this.socketData(res);
                      } else {
                        this.$message.error(" 更新失败 ");
                      }
                      setTimeout(() => {
                        this.updateDisabled = true;
                      }, 1000);
                    }
                  );
                }
              });
            } else {
              const data = {
                id: this.temp.id,
                name: this.temp.name,
                ad_id: this.temp.ad_id,
                url: this.temp.url,
                trade_id: this.temp.trade_id,
                trade_name: this.temp.trade_name,
                producer: this.temp.producer,
                time_length: this.temp.time_length,
                describe: this.temp.describe,
                video_ratio: this.temp.video_ratio,
                video_px: this.temp.video_px,
                video_type: this.video_type,
                file_md5: this.temp.file_md5
              };
              if (this.type === 2) {
                data["ad_name"] = this.temp.ad_name;
              } else {
                this.adOptions.forEach(item => {
                  if (item.id === this.temp.ad_id) {
                    data["ad_name"] = item.name;
                  }
                });
              }
              if (this.temp.check_status) {
                data["check_status"] = this.temp.check_status;
              }
              if (this.temp.check_remark) {
                data["check_remark"] = this.temp.check_remark;
              }
              const editVideoPath = {
                company: "STQ",
                api: "pc_AdVideo_editVideo",
                version: "1.0",
                data: data
              };
              this.socketApi.sendSock(JSON.stringify(editVideoPath), res => {
                if (res) {
                  this.socketData(res);
                } else {
                  this.$message.error(" 更新失败 ");
                }
                setTimeout(() => {
                  this.updateDisabled = true;
                }, 1000);
              });
            }
          }
        }
      });
    },
    // 区域行业选择
    getIndustry(pageNumber, search) {
      const industryIndexPath = {
        company: "STQ",
        api: "pc_trade_index",
        version: "1.0",
        data: {
          name: search,
          page: pageNumber,
          rows: this.pageSize,
          type: 2
        }
      };
      this.socketApi.sendSock(JSON.stringify(industryIndexPath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    getArea(pageNumber, search) {
      const areaIndexPath = {
        company: "STQ",
        api: "pc_region_index",
        version: "1.0",
        data: {
          // region_type: this.temp.region_type,
          name: search,
          page: pageNumber,
          rows: this.pageSize
        }
      };
      this.socketApi.sendSock(JSON.stringify(areaIndexPath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    // 广告主查询
    getadName(pageNumber, search) {
      const getAdNamePath = {
        company: "STQ",
        api: "pc_ad_getAdName",
        version: "1.0",
        data: {
          name: search,
          page: pageNumber,
          rows: this.pageSize
        }
      };
      this.socketApi.sendSock(JSON.stringify(getAdNamePath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "pc_AdVideo_getRequestList") {
            // 获取视频源列表
            this.total = resj.count;
            this.list = resj.data;
            this.listLoading = false;
          } else if (resj.api === "pc_AdVideo_checkVideo") {
            // 视频源审核
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "审核成功",
              type: "success",
              duration: 2000
            });
          } else if (resj.api === "pc_AdVideo_editVideo") {
            // 视频源编辑
            this.dialogFormVisible = false;
            this.updateLoading = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          } else if (resj.api === "pc_AdVideo_addVideo") {
            // 视频源添加
            this.dialogFormVisible = false;
            this.updateLoading = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
          } else if (resj.api === "pc_AdVideo_deleteVideo") {
            // 视频源删除
            this.getList();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          } else if (resj.api === "pc_trade_index") {
            // 行业模糊查询
            this.industryOptions = resj.data;
            this.industryCount = resj.count;
          } else if (resj.api === "pc_ad_getAdName") {
            // 广告主模糊查询
            this.adOptions = resj.data;
            this.adNameCount = resj.count;
          }
        }
      }
    },
    reductionTo(m, n) {
      if (!(m % 1 === 0) || !(n % 1 === 0)) {
        return false;
      } else if (m <= 0 || n <= 0) {
        return false;
      }
      var a = m;
      var b = n;
      a >= b ? ((a = m), (b = n)) : ((a = n), (b = m));
      if (m !== 1 && n !== 1) {
        for (var i = b; i >= 2; i--) {
          if (m % i === 0 && n % i === 0) {
            m = m / i;
            n = n / i;
          }
        }
      }
      return m + ":" + n;
    },
    // 上传视频
    async submitUpload(element, name) {
      const files = await this.$refs.file.files[0];
      this.files = files;
      if (this.$refs.file.files[0].size <= 400 * 1024 * 1024) {
        if (this.video_type === "1") {
          if (this.$refs.file.files[0].type === "video/mp4") {
            this.assignment("video", name, files);
          } else {
            this.$message.error("只能上传视频文件");
            this.$refs.file.value = null;
            return false;
          }
        } else {
          const index = this.$refs.file.files[0].name.lastIndexOf(".");
          const suffix = this.$refs.file.files[0].name
            .substr(index + 1)
            .toLowerCase();
          if (this.imageFile.indexOf(suffix) !== -1) {
            this.assignment("img", name, files);
          } else {
            this.$message.error("只能图片文件");
            this.$refs.file.value = null;
            return false;
          }
        }
      } else {
        this.$message.error("视频源大小不得超过400MB");
        this.$refs.file.value = null;
        return false;
      }
    },
    // 赋值
    assignment(type, name, files) {
      this.imgDataUrl = this.getObjectURL(files);
      this.temp[name] = this.imgDataUrl;
      this.$refs.file.value = null;
      // 获取视频的宽高
      if (type === "video") {
        const video = document.querySelector("#video_hideen");
        const _this = this;
        video.addEventListener("canplay", function() {
          _this.temp.time_length = parseInt(this.duration);
          _this.temp.video_ratio = _this.reductionTo(
            this.videoWidth,
            this.videoHeight
          );
          _this.temp.video_px = this.videoWidth + "*" + this.videoHeight;
        });
      } else {
        const img = new Image();
        img.src = this.imgDataUrl;
        const _this = this;
        img.onload = function() {
          _this.temp.video_ratio = _this.reductionTo(img.width, img.height);
          _this.temp.video_px = img.width + "*" + img.height;
        };
      }
    },
    changCode(name) {
      if (this.temp[name]) {
        this.$confirm("是否删除该视频源, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.temp[name] = "";
            this.temp.time_length = undefined;
            this.temp.video_ratio = "";
            this.temp.video_px = "";
            this.files = "";
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.temp[name] = "";
        this.temp.time_length = undefined;
        this.temp.video_ratio = "";
        this.temp.video_px = "";
        this.files = "";
      }
    },
    videoDel(name) {
      const video_name = { video_name: name };
      this.deleteFile(video_name, result => {
        // 编辑时删除oss里面的视频 不对返回值做处理
      });
    },
    beforeVideoClose(done) {
      if (this.video_type === "1") {
        var audio = document.querySelector("#video");
        audio.pause();
        audio.currentTime = 0;
      }
      done();
    },
    handleClose(done) {
      if (this.dialogStatus === "create" && this.temp.url) {
        const index = this.temp.url.lastIndexOf("/");
        const str = this.temp.url.substring(index + 1, this.temp.url.length);
        const video_name = { video_name: str };
        if (this.temp.id) {
          video_name["video_id"] = this.temp.id;
        }
        this.deleteFile(video_name, result => {
          if (result.data.code === 0) {
            this.$message.error(result.data.message);
          } else {
            this.temp[name] = "";
            this.temp.time_length = undefined;
            this.temp.video_ratio = "";
            this.temp.video_px = "";
          }
        });
      }
      this.resetTemp();
      this.getList();
      done();
    }
  }
};
</script>
